package com.stop.think.shiro.web.config;

import com.stop.think.shiro.dao.entity.EmpUsr;
import com.stop.think.shiro.service.EmpUsrService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;
import java.util.Set;

@Component
public class ShiroRealm extends AuthorizingRealm {
    @Resource
    private EmpUsrService empUsrService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ShiroToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        EmpUsr sysUsr = (EmpUsr) principals.getPrimaryPrincipal();
        Set<String> perms = empUsrService.findPermissionsByUsrId(sysUsr.getId());
        SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo();
        authInfo.setStringPermissions(perms);
        return authInfo;
    }

    /**

     * 认证（登录时调用）

     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String authToken = (String) token.getPrincipal();
        Optional<EmpUsr> empUsrOptional = empUsrService.findByToken(authToken);
        if (!empUsrOptional.isPresent()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        return new SimpleAuthenticationInfo(empUsrOptional.get(), authToken, getName());
    }
}
